const Base = require('./base.js');
const fs = require('fs');
const path = require('path');
const xlsx = require('node-xlsx');
const rename = think.promisify(fs.rename, fs);
const axios = require('axios');

module.exports = class extends Base {
  async indexAction() {
    const list = await this.model('filelist').getList();
    think.logger.debug(list);
    this.assign({ list });
    return this.display();
  }

  async sceniclistAction() {
    const fileId = this.ctx.query.id;
    const list = await this.model('sceniclist').where({fileId}).select();
    think.logger.debug(list);
    this.assign({ list });
    return this.display();
  }

  async fileuploadAction() {
    const file = this.file('file_data');
    think.logger.debug(file);
    const filePath = path.join(think.ROOT_PATH, `runtime/upload/${think.uuid()}/${file.name}`); ;
    think.mkdir(path.dirname(filePath));
    await rename(file.path, filePath);
    var sheets = xlsx.parse(filePath);
    const fileitemId = await this.model('filelist').addFile(file.name);
    this.handleData(sheets, fileitemId);
    return this.success({
      fileitemId
    });
  }

  async handleData(sheets, fileitemId) {
    const self = this;
    sheets.forEach(async(sheet) => {
      think.logger.debug(sheet);
      for (var rowId in sheet['data']) {
        var row = sheet['data'][rowId];
        if (row[4] !== '景区名') {
          await self.model('sceniclist').addScenicItem({
            name: row[4] || '默认',
            levle: row[5],
            province: row[0],
            city: row[1],
            district: row[2],
            fileId: fileitemId
          });
        }
      }
      const scenics = await this.model('sceniclist').getScenics(fileitemId);
      console.log(scenics);
      scenics.forEach(async(item, index) => {
        const keyword = item.name.match(/（(.+)）/);
        const result = await axios.get('https://restapi.amap.com/v3/place/text', {
          params: {
            keywords: keyword ? keyword[1] + '|' + item.name : item.name,
            types: '110000',
            city: item.city,
            children: 1,
            offset: 1,
            page: 1,
            extensions: 'all',
            key: '8f723fb25a4e9cbe592b9e17ffdcaaa3'
          }
        });
        if (result.data && result.data.pois.length) {
          const data = result.data.pois[0];
          await this.model('sceniclist').updateScenic(item.id, {
            province: data.pname,
            city: data.cityname,
            district: data.adname,
            status: 2
          });
          think.logger.debug('已更新: ' + item.name);
        }
      });
      await this.model('filelist').updateFileStatus({
        fileitemId,
        status: 2
      });
    });
  }
};
